package com.lecture.junit.tdd.example;

import java.util.Calendar;
import java.util.Date;

/**
 * User: Yury
 */
public abstract class LoginServiceState {


    public void login(IAccount acc, String password, LoginService context) throws AccountNotFoundException, AccountAlreadyRevokedException, PasswordException {

        if (acc.passwordMatches(password)) {
            if (acc.isRevoked()) {
                throw new AccountAlreadyRevokedException("Account is already revoked");
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_YEAR, -45);

            if (acc.getLastTouch().before(calendar.getTime())) {
            	acc.setRevoked(true);
            	return;
            }
            
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_YEAR, -30);
            if (acc.lastDatePasswordChanged().before(calendar.getTime())) {
            	context.promtChangePassword(acc);
            	return;
            }
            acc.setLoggedIn(true);
            acc.setLastTouch(new Date());
            context.setState(acc.getUserName(), new FirstFailedAttempt());
        } else {
            dealWithFailedAttempt(acc, context);
        }
    }

    protected abstract void dealWithFailedAttempt(IAccount acc, LoginService context);
}
